<?php

namespace app\admin\controller\charge;

use app\api\service\VbillService;
use app\common\controller\Backend;

/**
 * 店铺充值管理
 *
 * @icon fa fa-circle-o
 */
class Shopallchargeorder extends Backend
{

    /**
     * Shopallchargeorder模型对象
     * @var \app\admin\model\Shopallchargeorder
     */
    protected $model = null;
    protected $noNeedRight = ['refund'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Shopallchargeorder;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where('Shopallchargeorder.status','<>','paying')
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {



            }

            $result = array("total" => $list->total(), "rows" => $list->items());


            return json($result);
        }
        return $this->view->fetch();
    }

    public function refund()
    {

        $id = $this->request->param('id');


        $shopAllChargeModel = new \app\admin\model\Shopallchargeorder();
        $order = $shopAllChargeModel->where('id',$id)->find();
        if($order['status'] == 'refund'){
            $this->error("此订单已退款无需发起操作");
        }

        $userAllBalanceModel = new \app\admin\model\Userallbalance();
        $balance  = $userAllBalanceModel->userBalance($order['user_id']);
        if($balance < $order['get_amount']){

            $this->error("用户的余额已使用，不够退款金额");
        }
        $req = array();
        $req['mno']=$this->mno;
        $req['ordNo']= getOrderSn();
        $req['origOrderNo']= $order['order_no'];
        $req['amt']= $order['amount'];

        $vbillService = new VbillService();
        $ret = $vbillService->refund($req);
        $result = json_decode($ret,true);
        if($result['respData']['bizCode'] != "0000"){
            $this->error($result['respData']['bizMsg']);
        }
        $shopAllChargeModel->where('id',$order['id'])->update(['status'=>'refund']);
        $userAllBalanceModel->where('order_id',$order['id'])->where('from','charge')->delete();
        $this->success('退款成功');
    }


}
